package com.jiyongjun.component.utils;

import lombok.Getter;
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component;

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * <h2></h2>
 * <h3>描述：</h3>
 *
 * @author yongjun.jyj
 * @since 2022/7/14 18:18
 */
@Component("slsLogSpringContextHolder")
public class SpringContextHolder implements ApplicationContextAware {
    private volatile static ApplicationContext applicationContext;

    @Getter
    private static boolean initialized;

    private static final Map<Class<?>, Object> BEAN_CACHE = new ConcurrentHashMap<>();

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        SpringContextHolder.applicationContext = applicationContext;
        initialized = true;
    }

    @SuppressWarnings("unchecked")
    public static <T> T getBean(String name) {
        return (T) applicationContext.getBean(name);
    }

    @SuppressWarnings("unchecked")
    public static <T> T getBean(Class<T> clazz) {
        return (T) applicationContext.getBean(clazz);
    }

    @SuppressWarnings("unchecked")
    public static <T> T getBeanWithCache(Class<T> clazz) {
        return (T) BEAN_CACHE.computeIfAbsent(clazz, key -> getBean(clazz));
    }
}
